from fastapi import APIRouter,Depends
from tortoise.contrib.pydantic import pydantic_model_creator
from core import deps,verify_password

from scheams import User_Pydantic,UserIn_Pydantic,UserIn_Pydantic_WITHOUT_P,UserIn_Modify_Password,Response200,Response400
from models import User


user = APIRouter(tags=["用户相关"],dependencies=[Depends(deps.get_current_user)])

@user.get("/user",summary="获取当前用户")
async def user_info(user_obj: User = Depends(deps.get_current_user) ):
    
    return await User_Pydantic.from_tortoise_orm(user_obj)
    
@user.put("/user/{id}",summary="更新用户信息")
async def update_user(id: int,user_form: UserIn_Pydantic_WITHOUT_P):
    
    if await User.filter(id=id).update(**user_form.dict()):
        return {"msg","user update success"}
    
    return {"msg","user update error"}

@user.put("/user/modify_password/{id}",summary="修改密码")
async def modify_password(id: int,password_form: UserIn_Modify_Password):
    
    user = await User.filter(id=id).first()
    # 校验旧密码
    if not verify_password(password_form.oldPassword,user.password):
        return Response400(msg="原密码错误")
    # 校验新密码
    if(password_form.newPassword1 == password_form.oldPassword):
        return Response400(msg="新密码不能与旧密码相同")
    if(password_form.newPassword1 != password_form.newPassword2):
        return Response400(msg="输入密码不一致，请确认")
    
    # 修改密码
    user.password = password_form.newPassword1
    await user.save(update_fields=["password"])
    
    return Response200(msg="修改成功")

@user.get("/user/getOnlineUserCounts")
async def getOnlineUserCounts():
    return deps.global_user_cache.evict()

@user.get("/logout")
async def logout(temp = Depends(deps.logout)):
    return